package com.wangdong.network.ui;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.wangdong.network.ApiBase;
import com.wangdong.network.BaseRequest;
import com.wangdong.network.R;
import com.wangdong.network.Utils;
import com.wangdong.network.http.CMJsonCallback;
import com.wangdong.network.http.HttpSender;

import org.apache.http.Header;
import org.apache.http.cookie.Cookie;

import java.util.List;
import java.util.Locale;


public class MainActivity extends AppCompatActivity {

    private static final String TAG = "wangdong";
    private TextView text;//一个显示
    private Button button;//一个点击

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        text = (TextView) findViewById(R.id.textview_id);
        button = (Button) findViewById(R.id.button);
        //点击监听
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setData();//发起android-async-http 网络请求
            }
        });



    }


    public void setData() {

        AsyncHttpClient client = new AsyncHttpClient();
        PersistentCookieStore myCookieStore = new PersistentCookieStore(this);
        client.setCookieStore(myCookieStore);

        String url = "http://www.baidu.com/";
        client.get(url, new AsyncHttpResponseHandler() {

            /**
             * public abstract void onSuccess(int statusCode,
             cz.msebera.android.httpclient.Header[] headers,
             byte[] responseBody)
             当请求返回时被激发，重写以处理您自己的代码
             参数：
             statusCode-响应的状态代码
             headers-返回标头，如果有的话
             responseBody-服务器的http响应的正文
             * */
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                StringBuilder builder = new StringBuilder();
                for (Header h : headers) {
                    String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());

                    builder.append(_h);
                    builder.append("\n");
                }
                Log.e("wangdong", "onSuccess:参数一：int i = " + i + ";"
                        + "参数二：header【】header = " + builder.toString() + ";" + "参数三: byte[] bytes=" + new String(bytes));

            }

            /**
             * public abstract void onFailure(int statusCode,
             cz.msebera.android.httpclient.Header[] headers,
             byte[] responseBody,
             java.lang.Throwable error)
             当请求未能完成时发射，重写以处理您自己的代码
             参数：
             statusCode-返回http状态代码
             headers-返回标头，如果有的话
             responseBody-响应机构，如果有的话
             error-失败的根本原因
             * */
            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                Log.e("wangdong", "onFailure :参数一：int i = " + i + ";"
                        + "参数二：header【】header = " + headers.toString() + ";" + "参数三: byte[] bytes=" + new String(bytes));
            }
        });

    }

    private void sendHttp() {

        HttpSender.getInstance(this).get(getUrl(), getApi(), getRequest(), new CMJsonCallback<Object>() {
            @Override
            public void onSuccess(Object object) {
                Log.e("wangdong", object.toString());
                text.setText(object.toString());
            }

            @Override
            public void onError(int code, String message) {

            }

            @Override
            public void onFail(int code, String message) {

            }
        });
    }

    private BaseRequest getRequest() {
        BaseRequest request = new BaseRequest();

        return request;
    }

    private Class getApi() {
        // TODO Auto-generated method stub
        return ApiBase.class;
    }

    private String getUrl() {
        // TODO Auto-generated method stub
        return "/";
    }

    public void asynchttpPost() {
        String url = "http://apis.juhe.cn/mobile/get?";
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams params = new RequestParams();
        params.put("phone", "13666666666");
        params.put("key", "335adcc4e891ba4e4be6d7534fd54c5d");
        client.post(url, params, new AsyncHttpResponseHandler() {


            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                StringBuilder builder = new StringBuilder();
                for (Header h : headers) {
                    String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());

                    builder.append(_h);
                    builder.append("\n");
                }
                Log.e("wangdong", "onSuccess:参数一：int i = " + i + ";"
                        + "参数二：header【】header = " + builder.toString() + ";" + "参数三: byte[] bytes=" + new String(bytes));

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                StringBuilder builder = new StringBuilder();
                for (Header h : headers) {
                    String _h = String.format(Locale.US, "%s : %s", h.getName(), h.getValue());

                    builder.append(_h);
                    builder.append("\n");
                }
                Log.e("wangdong", "onFailure:参数一：int i = " + i + ";"
                        + "参数二：header【】header = " + builder.toString() + ";" + "参数三: byte[] bytes=" + new String(bytes));

            }
        });
    }

    /**
     * 获取标准 Cookie
     */
    private String getCookieText() {
        PersistentCookieStore myCookieStore = new PersistentCookieStore(MainActivity.this);
        List<Cookie> cookies = myCookieStore.getCookies();
        Log.d(TAG, "cookies.size() = " + cookies.size());
        Utils.setCookies(cookies);
        for (Cookie cookie : cookies) {
            Log.d(TAG, cookie.getName() + " = " + cookie.getValue());
        }
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < cookies.size(); i++) {
            Cookie cookie = cookies.get(i);
            String cookieName = cookie.getName();
            String cookieValue = cookie.getValue();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }
        Log.e("cookie", sb.toString());
        return sb.toString();
    }
}